<?php
namespace app\api\service;
use think\Request;
use app\api\model\Stock;
use app\api\model\StockList;
use app\api\model\Cargo;

class StockService {
    public function page($page = 1, $size = 10){
        $data 	= Request::instance()->get();
        $where 	= [];
        if (isset($data['alliance_id'])) {
            $where['alliance_id']= $data['alliance_id'];
        }
        empty($data['type']) || $where['type'] = $data['type'];

        !isset($data['audit']) || (is_numeric($data['audit']) && $where['audit'] = $data['audit']);
        !isset($data['audit']) || (is_numeric($data['status']) && $where['status'] = $data['status']);
        
        empty($data['order_no']) || $where['order_no'] = ['like','%'.$data['order_no']];

        $obj = Stock::with(['falliance', 'fwarehouse'])->where($where)
        ->order('id desc')
        ->paginate($size, false, ['page' => $page]);

        if ($obj->isEmpty()){
            return [];
        }
        return $obj->toArray();
    }

    // 获取订单的商品
    public function productByOrder() {
        $data = Request::instance()->get();
        if (!$data['id'] || empty($data['id'])) {
            return show(0, '错误参数', [], 200);
        }

        $result = StockList::where('stock_id', $data['id'])->order('id desc')->select();
        
        return show(1, 'ok', $result, 200);
    }

    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }

    // 加盟商提交订单
    public function save(){ 
        $param = Request::instance()->param();	//获取参数
        // $param = $p['params'];
        if (!is_numeric($param['id']))
        {
            $orderNo = $this->makeOrderNo();

            // 订单价格
            $price = 0;
            $products = $param['product'];
            for ($i = 0; $i< count($products); $i++) {
                // $products[$i] = json_decode($products[$i], true);
                $temp = $products[$i]['num'] * $products[$i]['price'];
                $price += $temp;
            }

            // 新增
            $obj = new Stock;
            $obj->type = $param['type'];
            $obj->remark = $param['remark'];
            $obj->alliance_id = $param['create_user'];
            $obj->total_price = $price;
            $obj->order_no = $orderNo;

            if(!$obj->save()){
                return show(0, '创建失败', [], 200);
            }

            $orderList = new StockList;
                
            // 添加订单id
            for ($i = 0; $i< count($products); $i++) {
                $products[$i]['stock_id'] = $obj->id;
            }
            
            $orderList->saveAll($products);

        }
        
        return show(1, '创建订单成功', [], 200);
    }

    public function delete($id){

    	if( Order::destroy($id, true) ){
            return show(1, '删除成功', [], 200);
        }
        
        return show(0, '删除失败', [], 200);
    }

    // 审批
    public function audit(){

        $param = Request::instance()->param();	//获取参数
        $check = array(1, 2); // 1 通过、2异常
        if (!$param['id'] || !$param['audit'] || empty($param['id']) || !in_array($param['audit'], $check)){
            return show(0, '操作失败', [], 200);
        }

        $obj = Stock::get($param['id']);

        $obj->audit = $param['audit'];

        if (!$obj->save()) {
            return show(0, '操作失败', [], 200);
        }

        return show(1, '操作成功', [], 200);
    }

    // 核实
    public function check() {

        $param = Request::instance()->param();	//获取参数
        $check = array(1, 2); // 1 通过、2异常
        if (!$param['id'] || !$param['status'] || empty($param['id']) || !in_array($param['status'], $check)){
            return show(0, '操作失败', [], 200);
        }

        $obj = Stock::get($param['id']);

        if ($obj->audit != 1){
            return show(0, '订单未审批', [], 200);
        }
        // 发货写入
        if (isset($param['logistics'])) {
            $obj->logistics = $param['logistics'];
            $obj->warehouse_id = $param['warehouse_id'];
            $obj->save();
        }else {
            // 退货 入库
            $obj->warehouse_id = $param['warehouse_id'];
            $obj->save();
        }

        $obj->status = $param['status'];

        $data = StockList::where('stock_id', $obj->id)
        ->select();
        // 商品 退货 
        if ($obj->type == 2){
            // 商品列表

            $tempArray = [];// 存放不存在商品
            foreach($data as $key => $item) {
                // $item->product_id  // 商品id
                // $obj->warehouse_id // 仓库id
                // 是否有
                $cargo = Cargo::where('product_id', $item->product_id)
                ->where('warehouse_id', $obj->warehouse_id)
                ->find();
                if ($cargo) {
                    // 存在商品 添加
                    $car = Cargo::get($cargo->id);
                    $car->num += $item->num;
                    $car->save();
                }else {
                    // 不存在商品
                    array_push($tempArray, [
                        'product_id' => $item->product_id,
                        'warehouse_id' => $obj->warehouse_id,
                        'num' => $item->num
                    ]);
                }
            }

            // 不存在商品新增
            if (count($tempArray)){
                $saveList = new Cargo;
                $saveList->saveAll($tempArray);
            }

        }else {
            // 销售出库 商品检测
            $tempReturn = []; // 销售更新商品数量
            foreach($data as $key => $item) {
                // $item->product_id  // 商品id
                // $item->num  // 销售商品数量
                // $obj->warehouse_id // 仓库id
                // 是否有
                $cargo = Cargo::where('product_id', $item->product_id)
                ->where('warehouse_id', $obj->warehouse_id)
                ->find();
                if ($cargo) {
                    // $cargo->num // 商品数量
                    if ($cargo->num >= $item->num) {
                        $tempNum = ($cargo->num - $item->num);
                        array_push($tempReturn, [
                            'id' => (int)$cargo->id,
                            'num' => $tempNum]);
                    }else {
                        return show(0, '仓库商品数量不足', [], 200); 
                    }
                }else {
                    // 不存在商品
                    return show(0, '仓库不存在该商品', [], 200); 
                }
            }
            $newList = new Cargo;
            $newList->isUpdate()->saveAll($tempReturn);
        }
        $obj->save();

        return show(1, '操作成功', [], 200); 
    }
}